<%@ page import="util.JDBC" %>
<%@ page import="util.JSON" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    //初始化
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    String userId="";
    try{
        userId=session.getAttribute("userId").toString();
    }catch (Exception ex){
        response.sendRedirect("login.jsp");
    }
    //处理请求
    //获取选课课程id
    String courseId=request.getParameter("courseId");
    //判断是否已经选过此课程
    String sql="SELECT count(*) as count FROM student_course WHERE studentId='"+userId+"' and courseId='"+courseId+"'";
    ResultSet rs=JDBC.executeQuery(sql);
    int count=0;
    while (rs.next()){
        count=rs.getInt("count");
    }
    if(count!=0){
        JSON json=new JSON("status","error");
        json.put("message","您已有该课程，请到我的课程中查看！");
        out.print(json.getJson());
    }else{
        //创建sql语句
        sql="insert into student_course(studentId,courseId) values('"+userId+"','"+courseId+"')";
        //测试数据库连接状态
        JDBC.connectionTest();
        //执行sql语句
        JDBC.executeUpdate(sql);
        JSON json=new JSON("status","success");
        json.put("message","选课成功");
        out.print(json.getJson());
    }
%>